package cn.bytengine.stem.utils;

import cn.hutool.core.lang.Tuple;
import cn.hutool.core.util.ObjectUtil;
import io.netty.util.NetUtil;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.util.Enumeration;
import java.util.Optional;

public abstract class Address {
    public static Tuple localAddress() {
        Optional<Tuple> opResult = NetUtil.NETWORK_INTERFACES
                .stream()
                .map(ni -> {
                    Enumeration<InetAddress> addresses = ni.getInetAddresses();
                    InetAddress address;
                    while (addresses.hasMoreElements()) {
                        address = addresses.nextElement();
                        if (address instanceof Inet4Address) {
                            return new Tuple(ni, address);
                        }
                    }
                    return null;
                })
                .filter(ObjectUtil::isNotNull)
                .findFirst();

        return opResult.orElse(null);
    }
}
